﻿@using Microsoft.EntityFrameworkCore.Internal
@using Flagrum.Web.Features.AssetExplorer.Base
@using Flagrum.Web.Persistence.Entities
@inject AppStateService AppState
@inject UriMapper Mapper
@inject FlagrumDbContext Context
@inject IStringLocalizer<RegenerateModal> L
@inject IWpfService WpfService

<AutosizeModal @ref="Modal" MaxWidth="420px">
    <HeaderView>
        <span class="text-grey-300 flex-grow">@L["Title"]</span>
        <span class="material-icons cursor-pointer" @onclick="CloseModal">cancel</span>
    </HeaderView>
    <BodyView>
        <div class="h-full">
            <span class="block mb-6">
                @L["Description"]
            </span>
            @if (Context.EarcMods.Any(m => m.IsActive))
            {
                <div class="rounded-md bg-accent1-900 border border-accent1-500 text-accent1-300 p-4 mt-4">
                    @L["ActiveModsWarning"]
                </div>
            }
            else
            {
                <Button Icon="refresh" Text="@L["RegenerateIndex"]" OnClickAsync="OnClick"/>
            }
        </div>
    </BodyView>
</AutosizeModal>

@code
{
    [CascadingParameter]
    public MainLayout MainLayout { get; set; }

    private AutosizeModal Modal { get; set; }

    public void Open()
    {
        if (AppState.Is3DViewerOpen)
        {
            WpfService.Set3DViewportVisibility(false);
        }

        Modal.Open();
    }

    private async Task OnClick()
    {
        Context.SetInt(StateKey.CurrentAssetNode, 1);
        AppState.RootGameViewNode = null;
        AppState.IsIndexing = true;
        
        MainLayout.CallStateHasChanged();
        CloseModal();

        await Task.Run(() =>
        {
            Mapper.RegenerateMap();
            Context.GetDependencies().StateManager.ResetState();
            AppState.LoadNodes();
            AppState.IsIndexing = false;
            InvokeAsync(() => MainLayout.CallStateHasChanged());
        });
    }

    private void CloseModal()
    {
        Modal.Close();

        if (AppState.Is3DViewerOpen)
        {
            WpfService.Set3DViewportVisibility(true);
        }
    }
}